import _ from 'underscore';
import TaskLineModel from './TaskLineModel.js';
import Radio from 'backbone.radio';
import {
    ajax_call
} from '../../tools.js';
import OrderableCollection from "../../base/models/OrderableCollection.js";

const TaskLineCollection = OrderableCollection.extend({
    model: TaskLineModel,
    initialize: function (options) {
        TaskLineCollection.__super__.initialize.apply(this, options);
        this.on('saved', this.channelCall);
        this.on('destroyed', this.channelCall);
    },
    channelCall: function () {
        var channel = Radio.channel('facade');
        channel.trigger('changed:task');
        this.trigger('synced');
    },
    load_from_catalog: function (sale_products) {
        var serverRequest = ajax_call(
            this.url + '?action=load_from_catalog', {
                sale_products: sale_products
            },
            'POST'
        );
        serverRequest.then(() => this.fetch()).then(() => this.channelCall());
    },
    ht: function () {
        var result = 0;
        this.each(function (model) {
            result += model.ht();
        });
        return result;
    },
    tvaParts: function () {
        var result = {};
        this.each(function (model) {
            var tva_amount = model.tva();
            var tva = model.get('tva');
            if (tva in result) {
                tva_amount += result[tva];
            }
            result[tva] = tva_amount;
        });
        return result;
    },
    ttc: function () {
        var result = 0;
        this.each(function (model) {
            result += model.ttc();
        });
        return result;
    },
    validate: function () {
        var result = {};
        this.each(function (model) {
            var res = model.validate();
            if (res) {
                _.extend(result, res);
            }
        });
        return result;
    }
});
export default TaskLineCollection;